﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using System.Configuration;

namespace MyDotNet.Dapper
{
    public class MySqlDapperHelper: IDapperHelper
    {
        private static string _connectionStrings =
            ConfigurationManager.ConnectionStrings["MyDotNet"].ToString();

        public MySqlDapperHelper()
        {

        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public List<T> Query<T>(string sql, object p)
        {
            using (IDbConnection conn = new MySqlConnection(_connectionStrings))
            {
                List<T> ctUserInfoList = conn.Query<T>(sql, p).ToList();
                return ctUserInfoList;
            }
        }


        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static bool Execute(string sql, object p)
        {
            using (IDbConnection conn = new MySqlConnection(_connectionStrings))
            {
                try
                {
                    conn.Execute(sql, p);
                    return true;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    return false;
                }
            }
        }

        /// <summary>
        /// 执行事务
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static bool ExecuteTransaction(string sql, object p)
        {
            using (IDbConnection conn = new MySqlConnection(_connectionStrings))
            {
                using (IDbTransaction tran = conn.BeginTransaction())
                {
                    try
                    {
                        conn.Execute(sql, p);
                        tran.Commit();
                        return true;
                    }
                    catch
                    {
                        tran.Rollback();
                        return false;
                    }
                }
            }
        }

    }
}